"""
财务数据可视化工具启动脚本
"""

import subprocess
import sys
import os
from pathlib import Path

def install_requirements():
    """安装依赖包"""
    requirements_file = Path(__file__).parent / "requirements.txt"
    
    if requirements_file.exists():
        print("正在安装依赖包...")
        try:
            subprocess.check_call([
                sys.executable, "-m", "pip", "install", "-r", str(requirements_file)
            ])
            print("依赖包安装完成！")
        except subprocess.CalledProcessError as e:
            print(f"依赖包安装失败: {e}")
            return False
    else:
        print("未找到requirements.txt文件")
        return False
    
    return True

def run_streamlit_app():
    """运行Streamlit应用"""
    app_file = Path(__file__).parent / "app.py"

    if not app_file.exists():
        print("未找到app.py文件")
        return False

    print("正在启动财务数据可视化工具...")
    print("请在浏览器中访问显示的URL")
    print("按Ctrl+C停止应用")

    # 设置环境变量跳过Streamlit邮箱输入
    env = os.environ.copy()
    env['STREAMLIT_BROWSER_GATHER_USAGE_STATS'] = 'false'

    try:
        subprocess.run([
            sys.executable, "-m", "streamlit", "run", str(app_file),
            "--server.port", "8501",
            "--server.address", "localhost",
            "--browser.gatherUsageStats", "false"
        ], env=env)
    except KeyboardInterrupt:
        print("\n应用已停止")
    except Exception as e:
        print(f"启动应用失败: {e}")
        return False

    return True

def main():
    """主函数"""
    print("=" * 50)
    print("A股财务数据可视化工具")
    print("=" * 50)
    
    # 检查Python版本
    if sys.version_info < (3, 8):
        print("错误: 需要Python 3.8或更高版本")
        return
    
    # 安装依赖
    if not install_requirements():
        print("请手动安装依赖包后重试")
        return
    
    # 运行应用
    run_streamlit_app()

if __name__ == "__main__":
    main()
